package com.mingqijia.gassafety.job.job.equipment;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author mby
 * @version 1.0.0
 * @ClassName RunningServicePeriodStrategyJob.java
 * @Description TODO
 * @createTime 2024年01月16日
 */
@Component
@Slf4j
public class EquipmentIndustryJob {


    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    public static final Integer pageSize = 1000;


    /**
     *   刷设备的行业类型
     */
    @XxlJob("equipmentIndustryJob")
    public ReturnT<String> equipmentIndustryJob(String param) {
        XxlJobLogger.log("XXLJOB-equipmentIndustryJob start..." );
        log.info("equipmentIndustryJob--start--------");
        try {
            execute();
        } catch (Exception e) {
            log.info("equipmentIndustryJob-error:{}", e);
        }
        log.info("equipmentIndustryJob--end--------");
        XxlJobLogger.log("XXLJOB-equipmentIndustryJob end..." );
        return ReturnT.SUCCESS;
    }

    private void execute() {
        // 查询所有有客户id的设备
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda()
            .eq(Dtu::getIsDeleted,0)
            .gt(Dtu::getConsumerId,0);

        int pageIndex = 1;
        long total = 0;
        do {
            Page<Dtu> pages = PageHelper.startPage(pageIndex, pageSize);
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            pageIndex++;
            total = pages.getTotal();
            if (!CollectionUtils.isEmpty(dtus)) {
                dtus.stream().forEach(dtu -> {
                    if (dtu.getConsumerId() != null && dtu.getConsumerId() > 0 && StringUtils.isBlank(dtu.getSectorType())) {
                        Consumer consumer = consumerMapper.selectById(dtu.getConsumerId());
                        if (consumer != null) {
                            dtu.setSectorType(consumer.getIndustryType());
                            dtuMapper.updateById(dtu);
                        }
                    }

                });
            }

        }while(total > (pageIndex - 1) * pageSize);
    }





}